/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package org.myontology.specialpages.configs;

import java.util.ArrayList;
import java.util.List;

import org.myontology.specialpages.EntryRow;
import org.openrdf.query.BindingSet;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.repository.RepositoryConnection;

import controller.sesameDataConnector.AbstractDataConnector;

/**
 * @author <a href="michael.hackl@sti2.at">Michael Hackl</a>
 * Project: Myontology - www.myontology.org
 * STI
 *
 * This is a base configuration for all special pages filled by a 
 * SERQL Statement
 * the query (setter or constructor) is used to obtain the list of entries for a special page, the RDF.TYPE and the RDFS.LABEL must be returned as result called 
* l and t 
* the entries are sorted by type
 *
 */
public abstract class SerqlSpecialPageConfig extends
		AbstractSerqlSpecialPageConfig {

	

	protected String query;
	
	public SerqlSpecialPageConfig(String key, String label,String query) {
		super(key, label);
		this.query = query;
	}

	public SerqlSpecialPageConfig(String key, String label) {
		super(key, label);
	}
	
	/**
	 * the query is used to obtain the list of entries for a special page, the RDF.TYPE and the RDFS.LABEL must be returned as result called 
	 * l and t 
	 * 
	 * @param query
	 */
	public void setQuery(String query) {
		this.query = query;
	}
	
	@Override
	protected List<EntryRow> select() {
		List<EntryRow> ret = new ArrayList<EntryRow>();
		
		
		try{
			RepositoryConnection con = AbstractDataConnector.getConnection();	
			try {
				logger.info("special page query: "+query);
				TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, query);
				TupleQueryResult result = tupleQuery.evaluate();
				try {
					if( result.hasNext()) {
								
						while (result.hasNext()) {
							BindingSet set = result.next();
							
							EntryRow row = writeSetToRow(set);
							
							ret.add(row);
						}
					}
				} finally {
					result.close();
				}
			} 
			catch (Exception e) {
				logger.error(e.getMessage());
			}
			finally {
				con.close();
			}
		} catch (Exception e) {
			logger.error("Error while selecting " + e.getMessage());
			return null;
		}
		return ret;
	}

	
	
}
